<template>
	<view class="newsList">
		<!-- 搜索 -->
		<view class="search">
			<input type="text" placeholder="搜索关键字" placeholder-class="text" v-model="key" class="inp" maxlength="11"
				@input="text" />
			<text class="iconfont icon-sousuo" @click="search"></text>
		</view>
		<NewsList :newsList="newsList" class="list"></NewsList>
		<view class="state" v-show="state">
			{{stateText}}
		</view>
	</view>
</template>

<script>
	import {
		Index
	} from "../../static/api/apis.js"
	import NewsList from "../../components/NewsList.vue"
	export default {
		data() {
			return {
				state: false,
				stateText: "下拉加载更多",
				page: 1,
				psize: 8,
				key: "",
				newsList: []
			};
		},
		components: {
			NewsList,
		},
		onReady() {
			document.querySelector('.uni-page-head__title').style.fontWeight = 'normal'
		},
		onLoad() {
			uni.showLoading({
				title: "加载中",
				mask: true
			})
			this.getNewsList()
		},
		// 上拉刷新
		onPullDownRefresh() {
			this.state = false
			this.newsList = []
			this.page = 1
			this.getNewsList()
		},
		// 下拉加载
		onReachBottom() {
			if (this.newsList.length < this.counts) {
				uni.showLoading({
					title: "加载中",
					mask: true
				})
				this.page++
				this.getNewsList()
			} else if (this.newsList.length === this.counts) {
				this.stateText = "已经到底了"
			}
		},
		methods: {
			// 搜索
			search() {
				this.state = false
				this.page = 1
				this.newsList = []
				uni.showLoading({
					title: "搜索中",
					mask: true
				})
				this.getNewsList()
			},
			// 获得资讯列表
			async getNewsList() {
				const res = await Index.newsList({
					page: this.page,
					psize: this.psize,
					key: this.key,
				})
				// 总数
				this.counts = res.data.counts
				this.$settime(() => {
					// 有数据
					if (res.errCode === 10000 && res.data.list.length > 0) {
						this.newsList = this.newsList.concat(res.data.list)
						// 数据少于一页或只有一页
						if (res.data.pageCounts === 1) {
							this.stateText = "已经到底了"
							console.log(111)
						} else {
							this.stateText = "下拉加载更多"
							console.log(222)
						}
					}
					// 没数据
					else {
						this.stateText = "已经到底了"
					}
					this.state = true
					uni.stopPullDownRefresh()
					uni.hideLoading()
					console.log('资讯列表', this.newsList)
				})
			},
			// 输入框
			text() {
				let self = this
				if (this.key.length === 11) {
					uni.showToast({
						title: "最多输入10个关键字",
						icon: "error",
						success() {
							self.$nextTick(() => {
								self.key = self.key.slice(0, 10)
							})
						}
					})
				}
			},
			// 返回上一个页面
			back() {
				uni.navigateBack({
					delta: 1
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	@import url(../../static/css/newsList.less);
</style>
